﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Threading;

namespace MyKnights
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private System.Threading.Mutex _mutex;

        public App()
        {
#if !DEBUG
            //全局主线程异常捕获
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; ;

            //全局子线程异常捕获
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
#endif
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string message = "程序子线程出现未捕获的异常，线程名称：" + Thread.CurrentThread.Name + "，异常描述：" + (e.ExceptionObject as Exception).Message;
            TUtil.LogHelper.WriteFile(message, Const.Path.ErrorFile);
            TUtil.LogHelper.WriteFile(e.ExceptionObject as Exception, Const.Path.ErrorFile);
            MessageBox.Show(message, "发生错误");

            //无限期阻塞该异常线程
            Thread.Sleep(-1);
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            TUtil.LogHelper.WriteFile(string.Format("未知错误:{0}:{1}", e.Exception?.StackTrace, e.Exception?.Message), Const.Path.ErrorFile);
            TUtil.LogHelper.WriteFile(string.Format("未知内部错误:{0}:{1}", e.Exception?.InnerException?.StackTrace, e.Exception?.InnerException?.Message), Const.Path.ErrorFile);

            MessageBox.Show(e.Exception.Message, "发生错误");

            //标记异常已经被处理
            e.Handled = true;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            //只能启动一个当前应用
            bool ret;
            _mutex = new System.Threading.Mutex(true, "mt_myknights", out ret);
            if (!ret)
            {
                Shutdown(0);
                return;
            }
            base.OnStartup(e);
        }
    }
}
